# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/25 3:00 下午
# @Author  : 白辉东
# @Mail    : masterbai2018@outlook.com
# @File    : test.py
# @Software: PyCharm

import numpy as np
import wave


# 读取波形数据
def audio_data():
    file_path = r"../test/output_02.wav"
    file = wave.open(file_path, "rb")

    audio_params = file.getparams()
    nchannels, sampwidth, framerate, nframes = audio_params[:4]
    # 读取波形数据
    str_data = file.readframes(nframes)
    file.close()

    print(nframes)
    print(nframes / 44100)

    # 将波形数据转换为数组
    wave_data = np.fromstring(str_data, dtype=np.short)

    # 设置数组的形状
    wave_data.shape = -1, nchannels
    wave_data = wave_data.T

    # 小波阀值去白噪，获取最终Y轴波形数组
    wave_data[abs(wave_data) < 20] = 0

    # 获取X轴时间数组
    times = np.arange(0, nframes) * (1.0 / framerate)

    return times, wave_data[0]


def zero_runs(a):
    iszero = np.concatenate(([0], np.equal(a, 0).view(np.int8), [0]))
    absdiff = np.abs(np.diff(iszero))
    ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
    return ranges


if __name__ == '__main__':
    times, wave_data = audio_data()
    result = zero_runs(wave_data)
    for i in result:
        time_tmp = i[1] - i[0]
        # 超过0.25秒则记录数值，44100一秒
        if time_tmp > 11025:
            check_data = np.zeros(time_tmp, dtype=int)
            check_time = times[i[0]:i[1]]
